<template>
  <div class="department-container">
    <div class="app-container">
      <PageTools>
        <template #left>
          <span>总记录数：{{ total }}</span>
        </template>
        <template #right>
          <!-- 自定义指令来实现按钮级别的权限控制 -->
          <!-- v-if="$store.state.user.userInfo.roles.points.includes('export')" -->

          <!-- v-allow是我们自己定义的指令。
          他的作用是：只有当vuex中保存的权限有export时，这个元素才被可见 -->
          <el-button
            type="warning"
            size="small"
            @click="$router.push('/import')"
            v-allow="'import'"
            >导入excel</el-button
          >
          <el-button type="danger" size="small" @click="hExportExcel"
            >导出excel</el-button
          >
          <el-button type="primary" size="small" @click="showAddDialog"
            >新增员工</el-button
          >
        </template>
      </PageTools>
      <el-card style="margin-top: 10px">
        <!-- 具体页面结构 -->
        <el-table
          border
          :data="employeesList"
          :default-sort="{ prop: 'workNumber' }"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" width="130">
            <template v-slot="scope">
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式">
            <template v-slot="scope">{{
              formatValue(scope.row.formOfEmployment)
            }}</template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="180">
            <template v-slot="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail?id=' + scope.row.id)"
                >查看</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="hAssignRole(scope.row.id)"
                >分配角色</el-button
              >
              <el-button type="text" size="small" @click="hDel(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="sizes, prev, pager, next"
            :total="total"
            :page-size="pageParams.size"
            :pager-count="5"
            :current-page="pageParams.page"
            :page-sizes="[2, 5, 10, 20, 50, 100]"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
          />
        </el-row>
      </el-card>

      <el-dialog :visible.sync="showDialog" v-if="showDialog" title="新增员工">
        <empDialog @doCancel="doCancel" @hSuccess="hSuccess"></empDialog>
      </el-dialog>

      <el-dialog
        :visible.sync="showRoleDialog"
        title="分配角色"
        v-if="showRoleDialog"
      >
        <assignRole
          @closeRoleDialog="closeRoleDialog"
          :cur-id="curId"
          @success="assignRoleSuccess"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployees, delEmployee } from "@/api/employees";
import empDialog from "./empDialog.vue";
import assignRole from "./assignRole";
import { transExportExcel, formatValue } from "@/utils/index";

export default {
  components: { empDialog, assignRole },
  data() {
    return {
      total: 1,
      employeesList: [],
      pageParams: {
        page: 1,
        size: 2,
      },
      showDialog: false,
      showRoleDialog: false,
      curId: "",
    };
  },
  created() {
    this.loadEmployees();
  },
  methods: {
    async loadEmployees() {
      const res = await getEmployees(this.pageParams);
      // console.log(res);
      this.employeesList = [...res.data.rows];
      this.total = res.data.total;
    },
    // 用户切换了页码
    hCurrentChange(curPage) {
      this.pageParams.page = curPage;
      this.loadEmployees();
    },
    // 用户切换了每页显示条目数
    hSizeChange(curSize) {
      console.log(curSize);
      this.pageParams.size = curSize;
      // 默认显示第一页
      this.pageParams.page = 1;
      this.loadEmployees();
    },
    formatValue(id) {
      return formatValue(id);
    },
    hDel(id) {
      console.log(id);
      this.$confirm("此操作将永久删除数据,是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 删除成功
          this.doDel(id);
        })
        .catch(() => {
          // 取消删除
          this.$message.info("已取消删除");
        });
    },
    async doDel(id) {
      try {
        const res = await delEmployee(id);
        console.log(res);
        this.$message.success(res.message);
        if (this.total % this.pageParams.size === 0) {
          this.pageParams.page--;
          this.pageParams.page = Math.max(1, this.pageParams.page);
        }
        this.loadEmployees();
      } catch (err) {
        console.dir(err);
        this.$message.error(err.message);
      }
    },
    showAddDialog() {
      this.showDialog = true;
    },
    doCancel() {
      this.showDialog = false;
    },
    hSuccess() {
      this.total++;
      this.pageParams.page = Math.ceil(this.total / this.pageParams.size);
      this.loadEmployees();
      this.showDialog = false;
    },
    hExportExcel() {
      import("@/vendor/Export2Excel").then(async (excel) => {
        // excel表示导入的模块对象
        console.log(excel);
        const res = await getEmployees(this.pageParams);
        const data = transExportExcel(res.data.rows);
        console.log(data);
        excel.export_json_to_excel({
          header: data.zhHeader, // 表头 必填
          data: data.data, // 具体数据 必填
          filename: "excel-list", // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: "xlsx", // 生成的文件类型
        });
        this.$message.success("导出成功");
      });
    },
    hAssignRole(id) {
      this.showRoleDialog = true;
      this.curId = id;
    },
    closeRoleDialog() {
      this.showRoleDialog = false;
    },
    assignRoleSuccess() {
      this.loadEmployees();
      this.showRoleDialog = false;
    },
  },
};
</script>
